from rest_framework.views import APIView
from rest_framework.response import Response

from oauth.models import QQUser
from .qq_sdk import *
from utils.jwt_token import generate
from utils import tjws
from .serializers import QQUserSerializer


class QQUrlView(APIView):
    """获取QQ登录授权页面的url"""

    def get(self, request):
        """
        提供用于qq登录的url
        """
        state = request.query_params.get('next')

        qqauth = OAuthQQ(state=state)

        url = qqauth.get_qq_login_url()

        return Response({"login_url": url})


class QQLoginView(APIView):
    """QQ登录后获取openid"""

    def get(self, request):
        # 获取code
        code = request.query_params.get('code')
        # 获取access_token
        qqauth = OAuthQQ()
        access_token = qqauth.get_access_token(code)
        # 获取openid
        openid = qqauth.get_openid(access_token)

        # 判断openid是否存在, 如果存在代表我已经授权过了，直接就可以返回状态保存
        try:
            qquser = QQUser.objects.get(openid=openid)
        except:
            # 不存在, 返回包含openid的access_token, 返回绑定页面
            access_token = tjws.dumps({"openid": openid}, SAVE_QQ_USER_TOKEN_EXPIRES)
            return Response({"access_token": access_token})
        else:
            # 存在， 直接返回状态保持
            return Response({
                'username': qquser.user.username,
                'user_id': qquser.user.id,
                'token': generate(qquser.user)
            })

    def post(self, request):
        """这个是授权之后到达绑定界面的视图"""

        # 获取参数
        data_dict = request.data
        # 校验参数
        serializer = QQUserSerializer(data=data_dict)
        if not serializer.is_valid():
            # 验证不通过就返回序列化器的errors，
            return Response({"message": serializer.errors})
        # 保存
        qquser = serializer.save()  # 返回反序列化后的对象
        # 响应
        return Response({
            'username': qquser.user.username,
            'user_id': qquser.user.id,
            'token': generate(qquser.user)
        })
